package com.lening.gateway.filter;

import com.lening.gateway.handler.BodyRewriteFunction;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.filter.NettyWriteResponseFilter;
import org.springframework.cloud.gateway.filter.factory.rewrite.ModifyResponseBodyGatewayFilterFactory;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @ToDo: 封装响应结果，long类型string
 * @Author：牛强
 * @date: 2024/6/11 17:12
 */
public class ResponseBodyFilter implements GlobalFilter, Ordered {

    public final static String ATTRIBUTE_IGNORE_TEST_GLOBAL_FILTER = "@ResponseBodyFilter";
    private GatewayFilter delegate;

    public ResponseBodyFilter(ModifyResponseBodyGatewayFilterFactory modifyResponseBodyGatewayFilterFactory,
                              BodyRewriteFunction rewriteFunction) {
        delegate = modifyResponseBodyGatewayFilterFactory
                .apply(new ModifyResponseBodyGatewayFilterFactory.Config()
                        .setRewriteFunction(rewriteFunction)
                        .setInClass(byte[].class)
                        .setOutClass(byte[].class));
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String uri = exchange.getRequest().getURI().toString();
        if (uri.contains("collect/pay/alipay")) {
            return chain.filter(exchange);
        }
        return delegate.filter(exchange, chain);
    }

    @Override
    public int getOrder() {
        return -2;
    }
}